import React, { useEffect, useState, useReducer } from "react";
import { useNavigate } from "react-router-dom";
import { Form, Table, Space } from "antd";
import axios from "axios";
import StartStopModel from "./StartStopModel";
import getFields from "./getFields";
import FormCom from "../../../common/FormCom";
import PaginationCom from "../../../common/PaginationCom";
import {businessTypeEnum,managementTypeEnum} from "../common/shopEum.js";

import "./index.css";

const initialState = {
  startStopModelStatus: false,
  operName: "",
  data: "",
  refresh: "",
};
const reducer = (state, action) => {
  console.log("模态框传入", action);
  switch (action.type) {
    case "changeStartStopModel":
      return {
        ...state,
        startStopModelStatus: action.status,
      };
    case "changeOperName":
      return {
        ...state,
        operName: action.name,
      };
    case "changeShopData":
      return {
        ...state,
        data: action.data,
      };
    case "changeRefresh":
      return {
        ...state,
        refresh: action.refresh,
      };
    default:
  }
};
/**选择每页多少条纪律的状态值 默认每页显示10条纪律*/
let pageNum = 10;
/**选择第几页的状态值 默认显示第一页*/
let pageIndex = 1;
  /**设置查询条件 */
let condition = {};
export default function PoiManageList() {
  let navigation = useNavigate();
  const [form] = Form.useForm();
  const [data, setData] = useState([]);
  /**
   * 设置操作模态框
   */
  const [store, dispatch] = useReducer(reducer, initialState);
 



  useEffect(() => {
    queryShops(); //无延迟加载 防止更新后一直停留在无数据页面
  }, [store.refresh]);
  useEffect(() => {
    setTimeout(function () {
      queryShops(); //延时加载 防止 读到更新前的数据
    }, 1000);
  }, [store.refresh]);

  function queryShops() {
    axios({
      headers: {
        tenantId: 500,
        userId: 11111,
      },
      method: "post",
      url: "http://localhost:9102/shop/search",
      data: {
        condition,
        pageIndex: pageIndex,
        pageSize: pageNum,
        sortFields: [
          { field: "enabled", asc: false },
          { field: "created_at", asc: false },
          { field: "last_modified_at", asc: false },
        ],
      },
    }).then((data) => {
      setData(data.data);
    });
  }
  /**
   * 查询请求格式化
   * @param  values
   */
  function formatJSON(values) {
    let condition = {
      keyword: values.name,
      managementTypes: [],
      businessTypes: [],
      enabled: null,
    };

    if (values.enabledSer === "all") {
      condition.enabled = null;
    } else {
      condition.enabled = values.enabledSer;
    }
    if (values.managementTypeSer === "all") {
      condition.managementTypes = [];
    } else {
      condition.managementTypes.push(values.managementTypeSer);
    }
    if (values.businessTypeSer === "all") {
      condition.businessTypes = [];
    } else {
      condition.businessTypes.push(values.businessTypeSer);
    }

    return condition;
  }

  const onFinish = (values) => {
    condition = formatJSON(values);
    queryShops();
  };

  const columns = [
    {
      title: "营业状态",
      dataIndex: "enabled",
      render: (item) =>
        item ? (
          <div className="stateDiv">营业中</div>
        ) : (
          <div className="stateDiv">停业中</div>
        ),
    },
    {
      title: "门店名",
      dataIndex: "name",
    },
    {
      title: "主营业态",
      dataIndex: "businessType",
      render: (item) => <>{businessTypeEnum[item]}</>,
    },
    {
      title: "管理类型",
      dataIndex: "managementType",
      render: (item) => <>{managementTypeEnum[item]}</>,
    },
    {
      title: "营业时间",
      dataIndex: "openingHours",
      render: (text) => text.openTime + "~" + text.closeTime,
    },
    {
      title: "营业面积",
      dataIndex: "businessArea",
    },
    {
      title: "操作",
      dataIndex: this,
      render: (text) => (
        <Space size="middle">
          <a
            onClick={() => {
              navigation("/poi-manage/editShop", { state: text });
            }}
          >
            编辑
          </a>
          {text.enabled ? (
            <a
              onClick={() => {
                dispatch({ type: "changeStartStopModel", status: true });
                dispatch({ type: "changeOperName", name: "stop" });
                dispatch({
                  type: "changeShopData",
                  data: { bno: text.businessNo, version: text.version },
                });
              }}
            >
              停用
            </a>
          ) : (
            <a
              onClick={() => {
                dispatch({ type: "changeStartStopModel", status: true });
                dispatch({ type: "changeOperName", name: "start" });
                dispatch({
                  type: "changeShopData",
                  data: { bno: text.businessNo, version: text.version },
                });
              }}
            >
              启动
            </a>
          )}
        </Space>
      ),
    },
  ];

  return (
    <div>
      <FormCom
        onFinish={onFinish}
        initialValues={{
          businessTypeSer: "all",
          managementTypeSer: "all",
          enabledSer: "all",
        }}
        name="门店List页面"
        getFields={getFields()}
        resetFields={() => {
          condition = {};
          queryShops();
          form.resetFields();
        }}
      />

      <Table
        pagination={false}
        dataSource={data.records}
        columns={columns}
        rowKey="id"
      />

      <PaginationCom
        totalCount={data.totalCount}
        pageNum={pageNum}
        changePageIndex={(num) => {
          console.log("改变pageIndex", num);
          pageIndex = num;
          queryShops();
        }}
        changePageNum={(num) => {
          console.log("改变pageNum", num);
          pageNum = num;
          queryShops();
        }}
      />
      <StartStopModel store={store} dispatch={dispatch} />
    </div>
  );
}
